import { useRef } from "react";
import { Button, Card, message, Popconfirm, Table } from "antd";
import dayjs from "dayjs";
import { CouresLabelMap } from "@/enums/school/course.enum";
import { TeacherTitleEnum } from "@/enums/school/teacher.enum";
import { exportTeacherListApi, removeTeacherApi } from "@/api/school/teacher";
import EditDrawerCard from "./EditDrawerCard";
import type { TableProps } from "antd";
import type { TableDataType, TabelCardPropsType } from "../types/tableCard.type";
import type { DrawerRefType } from "../types/editDrawerCard.type";

const TableCard = (props: TabelCardPropsType) => {
  const drawerRef = useRef<DrawerRefType>(null);
  const [messageApi, contextHolder] = message.useMessage();

  const columns: TableProps<TableDataType>["columns"] = [
    { title: "教师姓名", fixed: "left", width: 100, dataIndex: "teacherName" },
    { title: "负责课程", width: 100, render: (_, { course }) => CouresLabelMap[course] },
    { title: "职称", width: 120, render: (_, { teacherTitle }) => TeacherTitleEnum[teacherTitle] },
    {
      title: "性别",
      width: 60,
      render: (_, { gender }) => (gender === 1 ? "男" : gender === 2 ? "女" : "--"),
    },
    { title: "联系电话", width: 140, dataIndex: "teacherPhone" },
    { title: "现居住址", dataIndex: "currentAddress" },
    { title: "身份证号", dataIndex: "idCard" },
    { title: "身份证地址", dataIndex: "idCardAddress" },
    { title: "生日", width: 140, dataIndex: "birthday" },
    { title: "创建人", width: 140, dataIndex: "createBy" },
    {
      title: "创建时间",
      width: 140,
      dataIndex: "createDate",
      render: (_, { createDate }) => dayjs(createDate).format("YYYY-MM-DD HH:mm:ss"),
    },
    {
      title: "操作",
      key: "action",
      fixed: "right",
      width: 140,
      render: (_, record) => (
        <>
          <Button type="link" className="p-0" onClick={() => onUpdate(record)}>
            编辑
          </Button>
          <Popconfirm
            title="提示"
            description="请确认是否删除当前数据?"
            onConfirm={() => onRemove(record.id)}
            okText="Yes"
            cancelText="No"
          >
            <Button type="link" className="p-0 ml-8">
              删除
            </Button>
          </Popconfirm>
        </>
      ),
    },
  ];

  const onOpen = () => {
    drawerRef.current?.onOpen();
  };
  const onClose = () => {
    props.onReset();
  };
  const onUpdate = (record: TableDataType) => {
    drawerRef.current?.onOpen(record);
  };
  const onRemove = async (id: number) => {
    await removeTeacherApi(id);
    messageApi.success("删除成功");
    setTimeout(() => {
      props.onReset();
    }, 500);
  };
  const onExport = async () => {
    const { data } = await exportTeacherListApi<{ data: Buffer }>();
    const uint8Array = new Uint8Array(data.data);
    const blob = new Blob([uint8Array], { type: "application/octet-stream" });
    const a = document.createElement("a");
    const blobUrl = URL.createObjectURL(blob);
    a.href = blobUrl;
    a.download = `教师表_${+new Date()}.xlsx`;
    a.click();
    window.URL.revokeObjectURL(blobUrl);
  };
  
  return (
    <Card className="mt-16">
      {/*  */}
      {contextHolder}
      <div>
        <Button type="primary" onClick={onOpen}>
          新增
        </Button>
        <Button className="ml-8" onClick={onExport}>
          导出
        </Button>
      </div>
      {/*  */}
      <Table
        className="mt-8"
        columns={columns}
        dataSource={props.tabelData}
        scroll={{ x: 1700 }}
        rowKey="id"
        expandable={{
          expandedRowRender: record => {
            return (
              <div>
                <p className="font-bold text-14">教师简介：</p>
                <p className="mt-4 indent-[2em]">{record.teacherProfile}</p>
              </div>
            );
          },
          rowExpandable: record => Boolean(record.teacherProfile),
        }}
        {...props.tableProps}
      />
      {/* 新增编辑 */}
      <EditDrawerCard ref={drawerRef} onClose={onClose} />
    </Card>
  );
};
export default TableCard;
